#coding=utf-8
import platform
from ctypes import *
from threading import local

#load so ,
#Init() , Caminit(), CmeraGetimage Buffer
def loadLibMVSDK():
    import os
    is_x86 = (platform.architecture()[0] == '32bit')
    root_dir = os.path.abspath(os.path.dirname(__file__))
    lib_name = ''
    if is_x86:
        lib_name = 'x86/libMVSDK.so'
    else:
        lib_name = 'x64/libMVSDK.so'
    lib_path = os.path.join(root_dir, '../lib/' , lib_name)
    _sdk = cdll.LoadLibrary(os.path.abspath(lib_path))
    return _sdk

# SDK动态库
_sdk = None

def _Init():
    global _sdk

    _sdk = loadLibMVSDK()

_Init()

def _string_buffer_to_str(buf):
	s = buf if isinstance(buf, type(b'')) else buf.value

	for codec in ('gbk', 'utf-8'):
		try:
			s = s.decode(codec)
			break
		except UnicodeDecodeError as e:
			continue

	if isinstance(s, str):
		return s
	else:
		return s.encode('utf-8')


class MvStructure(Structure):
	def __str__(self):
		strs = []
		for field in self._fields_:
			name = field[0]
			value = getattr(self, name)
			if isinstance(value, type(b'')):
				value = _string_buffer_to_str(value)
			strs.append("{}:{}".format(name, value))
		return '\n'.join(strs)

	def __repr__(self):
		return self.__str__()

	def clone(self):
		obj = type(self)()
		memmove(byref(obj), byref(self), sizeof(self))
		return obj

#图像帧头信息
class tSdkFrameHead(MvStructure):
	_fields_ = [
		("uiMediaType", c_uint),      # 图像格式,Image Format
		("uBytes", c_uint),           # 图像数据字节数,Total bytes
		("iWidth", c_int),            # 宽度 Image height
		("iHeight", c_int),           # 高度 Image width
		("iWidthZoomSw", c_int),      # 软件缩放的宽度,不需要进行软件裁剪的图像，此变量设置为0.
		("iHeightZoomSw", c_int),     # 软件缩放的高度,不需要进行软件裁剪的图像，此变量设置为0.
		("bIsTrigger", c_int),        # 指示是否为触发帧 is trigger
		("uiTimeStamp", c_uint),      # 该帧的采集时间，单位0.1毫秒
		("uiExpTime", c_uint),        # 当前图像的曝光值，单位为微秒us
		("fAnalogGain", c_float),     # 当前图像的模拟增益倍数
		("iGamma", c_int),            # 该帧图像的伽马设定值，仅当LUT模式为动态参数生成时有效，其余模式下为-1
		("iContrast", c_int),         # 该帧图像的对比度设定值，仅当LUT模式为动态参数生成时有效，其余模式下为-1
		("iSaturation", c_int),       # 该帧图像的饱和度设定值，对于黑白相机无意义，为0
		("fRgain", c_float),          # 该帧图像处理的红色数字增益倍数，对于黑白相机无意义，为1
		("fGgain", c_float),          # 该帧图像处理的绿色数字增益倍数，对于黑白相机无意义，为1
		("fBgain", c_float),          # 该帧图像处理的蓝色数字增益倍数，对于黑白相机无意义，为1
	]

def CameraInit(pCameraInfo, emParamLoadMode = -1, emTeam = -1):
	pCameraHandle = c_int()
	err_code = _sdk.CameraInit(byref(pCameraInfo), emParamLoadMode, emTeam, byref(pCameraHandle))

	return pCameraHandle.value
def CameraInit_Hawk(h_camera):
	ret = _sdk.CameraInit_Hawk(h_camera)
	return ret

def CameraGetImageBuffer(hCamera, wTimes):
	#pointer
	# pbyBuffer = c_void_p()
    pbyBuffer = create_string_buffer((3*262144))
    print(sizeof(pbyBuffer))
    #struct pointer
    pFrameInfo = tSdkFrameHead()
    #指针为啥用 byref?
    err_code = _sdk.CameraGetImageBuffer(hCamera, byref(pFrameInfo), pbyBuffer, wTimes)
    # print(err_code)
    # #指针指向的值????
    return (pbyBuffer, pFrameInfo)

def Init():
    ret = _sdk.init()

    return ret